import traceback
from typing import Optional, Any

from ctaf_core.bus_server_bundle.bus_service_server import BusServiceServer
from ctaf_core.ctaf_objects.base_bundle import BaseBundle
from ctaf_core.ctaf_resources.ctaf_settings import CTAFsettings
from ctaf_core.ctaf_objects.base_event import BaseEvent, MsgEvent
from ctaf_core.log_trace_bundle.logging import LogRecorder, LoggerFactory


class BusServerBundle(BaseBundle):
    """
    """
    log_recorder: LogRecorder = LoggerFactory.get_logger()

    def __init__(self) -> None:
        super().__init__("BusServerBundle")
        self.server: Optional[BusServiceServer] = None
        self.bus_service_server_setting_filename: str = CTAFsettings.get_setting("busServiceServerSettingFilename")
        self.init_server(self.bus_service_server_setting_filename)

    def load_bundle(self):
        self.start()

    def init_server(self, bus_service_server_setting_filename: str) -> None:
        """初始化BusServiceServer"""
        self.server = BusServiceServer(bus_service_server_setting_filename)


    def start(self) -> bool:
        """启动BusServiceServer服务"""
        if self.server.is_active():
            BusServerBundle.log_recorder.write_info_log("BusServiceServer is running")
            return False

        try:
            self.server.start()
        except:  # noqa
            msg: str = traceback.format_exc()
            BusServerBundle.log_recorder.write_info_log(f"BusServiceServer boot failed：{msg}")
            return False

        BusServerBundle.log_recorder.write_info_log("BusServiceServer boot success")
        return True

    def stop(self) -> bool:
        """停止BusServiceServer服务"""
        if not self.server.is_active():
            BusServerBundle.log_recorder.write_info_log("BusServiceServer is not running")
            return False
        self.server.stop()
        BusServerBundle.log_recorder.write_info_log("BusServiceServer stopped")
        return True

    def unload_bundle(self):
        self.stop()

    #从本地事件驱动引擎拿到的事件若是消息事件（MsgEvent），则通过分布式总线服务发布
    def publish_msg(self, event: BaseEvent) -> Any:
        if isinstance(event, MsgEvent):
            if self.server.is_active() :
                BusServerBundle.log_recorder.write_info_log("BusServer push a remote MsgEvent")
                self.server.publish(event)